package cn.milk.servlet;

import cn.milk.dao.UserDAO;
import org.json.JSONObject;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/UserController")
public class UserController extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String action = request.getParameter("action");
          String keyword = request.getParameter("keyword"); // 获取搜索关键字
        if ("list".equals(action)) {
            int page = Integer.parseInt(request.getParameter("page"));
            JSONObject result = null;
            try {
                result = UserDAO.getUserList(page, keyword);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(result.toString());
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String action = request.getParameter("action");

        if ("add".equals(action)) {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            int role = Integer.parseInt(request.getParameter("role"));
            boolean success = false;
            try {
                success = UserDAO.addUser(username, password, role);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            response.getWriter().write(success ? "success" : "fail");
        } else if ("delete".equals(action)) {
            int id = Integer.parseInt(request.getParameter("id"));
            boolean success = false;
            try {
                success = UserDAO.deleteUser(id);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            response.getWriter().write(success ? "success" : "fail");
        } else if ("edit".equals(action)) {
            int id = Integer.parseInt(request.getParameter("id"));
            String username = request.getParameter("username");
            boolean success = false;
            try {
                success = UserDAO.updateUser(id, username);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            response.getWriter().write(success ? "success" : "fail");
        }
    }
}
